package com.mz.ozy.activity.find;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.TextView;

import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.mz.ozy.R;
import com.mz.ozy.adapter.ReleaseMsgAdapter;
import com.mz.ozy.base.BaseActivity;
import com.mz.ozy.bean.DynamicsDetailBean;
import com.mz.ozy.bean.EventBean;
import com.mz.ozy.constants.Constants;
import com.mz.ozy.mvp.presenter.PostDynamicPresenter;
import com.mz.ozy.mvp.view.PostDynamicContract;
import com.mz.ozy.utils.EmojiUtils;
import com.mz.ozy.utils.FullyGridLayoutManager;
import com.mz.ozy.utils.LocationHelper;
import com.mz.ozy.utils.QiNiuManger;
import com.mz.ozy.utils.SPUtils;
import com.mz.ozy.utils.ToastUtils;
import com.mz.ozy.utils.Utils;
import com.qiniu.android.http.ResponseInfo;
import com.qiniu.android.storage.UpCompletionHandler;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import butterknife.BindView;
import butterknife.ButterKnife;

public class PostDynamicActivity extends BaseActivity<PostDynamicContract.View, PostDynamicPresenter> implements PostDynamicContract.View {

    public static final String TYPE_ADDRESS_INFO = "TYPE_ADDRESS_INFO";
    private static final int MAX_TEXT_NUM = 500;

    private int maxSelectNum = 9;
    private ReleaseMsgAdapter adapter;

    @BindView(R.id.rv_post_dynamic)
    RecyclerView mRvPostDynamic;
    @BindView(R.id.tv_location_choose)
    TextView mTvLocationChoose;
    @BindView(R.id.tv_post_dynamic)
    TextView mTvPostDynamic;
    @BindView(R.id.et_post_dynamic_msg)
    EditText mEtPostDynamicMsg;
    @BindView(R.id.tv_word_number_hint)
    TextView mTvWordNumberHint;
    @BindView(R.id.tv_dynamic_topic)
    TextView mTvDynamicTopic;
    private String mUid;
    private String mTopic;
    private InputMethodManager manager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_post_dynamic);
//        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN
//                | WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
        ButterKnife.bind(this);
        initTitle3();
        tvTitle.setVisibility(View.GONE);
        tvCenterTitle.setText("发布动态");
        mUid = getIntent().getStringExtra("id");
        mTopic = getIntent().getStringExtra("topic");
        manager = ((InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE));
        initView();
        initEvents();
    }

    private void initEvents() {
        tvBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mEtPostDynamicMsg.requestFocus();
                manager.hideSoftInputFromWindow(mEtPostDynamicMsg.getWindowToken(), 0);
                finish();
            }
        });
        mTvDynamicTopic.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mEtPostDynamicMsg.requestFocus();
                manager.hideSoftInputFromWindow(mEtPostDynamicMsg.getWindowToken(), 0);
                finish();
            }
        });
        mTvLocationChoose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
//                Intent intent = new Intent(PostDynamicActivity.this, LocationActivity.class);
//                startActivityForResult(intent, 1001);
            }
        });

        rightTextView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //内容
                //内容
                String messge = mEtPostDynamicMsg.getText().toString();
                if (TextUtils.isEmpty(messge)) {
                    ToastUtils.showToast("请输入您的想法");
                    return;
                }
                String submitImg = "";
                if (img.size() == 0) {
                    submitImg = "";
                } else {
                    for (String str : img) {
                        submitImg = submitImg + str + ",";
                    }
                    submitImg = submitImg.substring(0, submitImg.length() - 1);
                }
                mPresenter.onPostDynamic(PostDynamicActivity.this, mUid, submitImg, EmojiUtils.escape(messge), LocationHelper.getCity());
            }
        });
        mEtPostDynamicMsg.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }

            @Override
            public void afterTextChanged(Editable editable) {
//                int spacenum = MAX_TEXT_NUM - editable.toString().length();
                mTvWordNumberHint.setText(editable.toString().length() + "/500");
            }
        });
    }

    private void initView() {
        FullyGridLayoutManager gridLayoutManager = new FullyGridLayoutManager(this, 4, GridLayoutManager.VERTICAL, false);
        mRvPostDynamic.setLayoutManager(gridLayoutManager);
        adapter = new ReleaseMsgAdapter(new ArrayList<String>(), R.mipmap.post_msg_plus_pic);
        adapter.setSelectMax(maxSelectNum);
        mRvPostDynamic.setAdapter(adapter);
        adapter.setOnAddPicClickListener(new ReleaseMsgAdapter.onAddPicClickListener() {
            @Override
            public void onAddPicClick() {
                //相册
                PictureSelector.create(PostDynamicActivity.this)
                        .openGallery(PictureMimeType.ofImage())
                        .maxSelectNum(maxSelectNum - adapter.getData().size())
                        .minSelectNum(1)
                        .imageSpanCount(4)
                        .selectionMode(PictureConfig.MULTIPLE)
                        .forResult(PictureConfig.CHOOSE_REQUEST);
            }

            @Override
            public void onRemovePicClick(int index) {
                img.remove(index);
            }
        });
        if (!TextUtils.isEmpty(mTopic)) {
            mTvDynamicTopic.setVisibility(View.VISIBLE);
            mTvDynamicTopic.setText("#" + mTopic + "#");
        }
    }

    //用户选中图片后，拿到回掉结果
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == PictureConfig.CHOOSE_REQUEST && resultCode == RESULT_OK) {
            List<LocalMedia> images = PictureSelector.obtainMultipleResult(data);
            List<String> uploadlist = Utils.convertToImageList(images);
            if (uploadlist != null && uploadlist.size() > 0) {
                for (String str : uploadlist) {
                    uploadAvatar(str);
                }
            }
        }
    }

    private List<String> img = new ArrayList<>();

    private void uploadAvatar(final String path) {
        final String qiniuToken = SPUtils.getInstance(this).getString(Constants.SPName.QINIU_TOKEN, "");
        QiNiuManger.getInstance().getUploadManager().put(path, QiNiuManger.getInstance().getKeyName(), qiniuToken, new UpCompletionHandler() {
            @Override
            public void complete(String key, ResponseInfo info, JSONObject response) {
                if (info.isOK()) {
                    img.add(key);
                    adapter.addNewItem(path);
                }
            }
        }, null);
    }

    @Override
    public void onPostDynamicSuccess() {
        ToastUtils.showToast("发表动态成功");
        EventBus.getDefault().post(new EventBean(Constants.EventCode.POST_DYNAMICS, null));

        finish();
    }

    @Override
    public void getFiendDynamicsDetail(DynamicsDetailBean result) {
        DynamicsDetailBean.DynamicsDetail map = result.getMap();
        if (map != null) {
            if (!TextUtils.isEmpty(map.getTitle())) {
                mTvDynamicTopic.setVisibility(View.VISIBLE);
                mTvDynamicTopic.setText(map.getTitle());
            }
        }
    }
}
